import axios from 'axios';
import Vue from 'vue';
import $ from 'jquery';

export default {

    init: function () {

        Vue.prototype.$http = Object.assign(this, axios);
    },

    methods: {
        GET: "get",
        POST: "post",
        DELETE: "delete",
        PUT: "put",
        PATCH: "patch",
        OPTIONS: "options",
        HEAD: "head"
    },

    contentType: {
        json: 'application/json',
        xml: 'application/xml',
        file: 'text/plain',
        html: 'text/html',
        form: 'application/x-www-form-urlencoded; charset=UTF-8',
    },

    responseType: {
        json: 'json',
        arraybuffer: 'arraybuffer',
        blob: 'blob',
    },

    /**
     * @Author renminghe
     * @Description // http请求函数
     * @Date 18:46 2018-12-26
     * @Param method option String 请求方式 default get
     * @Param url required String 请求地址
     * @Param data option 请求参数 default ""
     * @Param ContentType option 请求数据格式 default json
     * @Param ResponseType option 相应数据格式 default json
     * @return PromiseObj
     **/
    query: function (params) {

        if (!params.url) {

            return "url is null";
        }

        let method = params.method ? params.method : this.methods.GET;
        let url = params.url;
        let data = params.data;
        let ContentType = params.contentType;
        let ResponseType = params.responseType;


        let ContentTypeStr = this.contentType[ContentType] ? this.contentType[ContentType] : 'application/json';
        let ResponseTypeStr = this.responseType[ResponseType] ? this.responseType[ResponseType] : 'json';

        return new Promise((resolve, reject) => {

            axios({
                method: method,
                url: url,
                data: data,
                headers: {'Content-type': ContentTypeStr},
                responseType:ResponseTypeStr,
            }).then((res) => {

                if (res.data) resolve(res.data);

            }).catch((error) => reject('Error: request ' +  url + " " + error.message));
        });

    },

    ajQuery: (params) => {

        if (!params.url) {

            return "url is null";
        }

        let method = params.method ? params.method : this.methods.GET;
        let url = params.url;
        let data = params.data;

        return new Promise((resolve, reject) => {

            $.ajax({
                url: url,
                data: data,
                type: method,
                success: (result)=> {
                    resolve(result);
                },
                error: (err) => {
                    reject(err);
                },
            });
        });
    },
}